/**************************************************************************************
*
*	Copyright (C) 2010 - 2012 Brent Andrew O. Chua - See LICENSE.txt for more info.
*		
*	Filename	- ThreadTask.h
*
*	Description - 
*
*	Comments	-
*
*	Modification History:
*			Name			   Date					Description
*			MrCodeSushi	-	08/11/2012	-	Creation of this file.
**************************************************************************************/
#ifndef _PSX_THREAD_TASK_H_
#define _PSX_THREAD_TASK_H_

#include "PulseSTD.h"
#include "AtomicInt.h"
#include "Array.h"

namespace Pulse
{
	// Use whole cache line to avoid false-sharing
	class PSX_CacheLineAligned TaskStatus
	{
	public:

		//TaskStatus( void );

		BOOL IsComplete( void ) { return m_activeTaskCount == 0; };

		BOOL IsBusy( void ) { return m_activeTaskCount != 0; }

		void SetBusy( void ) { ++m_activeTaskCount; }

		void SetDone( void ) { --m_activeTaskCount; }

	private:

		AtomicInt m_activeTaskCount;
	};

	class ThreadTask
	{
	public:

		// This class creates its own TaskStatus
		ThreadTask( void );

		// TaskStatus comes from the parent ThreadTAsk
		ThreadTask( TaskStatus *pStatus );
 
		virtual ~ThreadTask( void );

		virtual BOOL Run( void ) = 0;

		TaskStatus * GetTaskStatus( void ) { return m_pTaskStatus; }

		// NOTE: Keep half the work and put the other half in a new task.
		virtual BOOL Split( ThreadWorker *pWorker ) { return FALSE; }

		// NOTE: Returns a sub part of the task.
		virtual BOOL PartialPop( ThreadTask **ppTask ) { return FALSE; }

		// NOTE: Share work across all threads.
		virtual BOOL Spread( TaskScheduler *pScheduler ) { return FALSE; }

		BOOL IsComplete( void ) { return m_pTaskStatus->IsComplete(); }

		// NOTE: Is this the parent task.
		BOOL IsMainTask( void ) { return m_bStatusOwner; }

	protected:

		BOOL m_bStatusOwner;
		TaskStatus *m_pTaskStatus;

	};
}

#endif /* _PSX_THREAD_TASK_H_ */